<template>
  <div clas="clerk_tags__">
    <div class="tags_cards">
      <el-tabs v-model="cards.now" type="card" @tab-click="handleClickCard">
        <el-tab-pane
          v-if="EditMode.m == EditMode.AddNewClerk || EditMode.m == EditMode.EditClerk"
          :name="cards.baseInfo">
          <span slot="label">
            <i class="el-icon-s-custom"></i>
            基本信息
          </span>
          <i v-if="isFetching" class="el-icon-loading" color="#409EFF"></i>
          <div v-else class="tags_xingqu">
            <clerk-info ref="refClerkInfo" :mode="EditMode.m" :cdata="clerkEditVo"></clerk-info>
          </div>
        </el-tab-pane>
        <el-tab-pane :name="cards.tagXingQu">
          <span slot="label">
            <i class="el-icon-star-on"></i>
            兴趣标签
          </span>
          <i v-if="isFetching" class="el-icon-loading" color="#409EFF"></i>
          <div v-else class="tags_xingqu">
            <div v-for="item in tagsXingQu" class="tags_xq_item" @click.stop="handleChangeTagXingQu(item.name, $event)">
              <span class="name">{{ item.tag }}</span>
              <el-rate v-model="clerkVo[item.name]" :max="3"></el-rate>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :name="cards.tagXiaoFei">
          <span slot="label">
            <i class="el-icon-s-goods"></i>
            消费标签
          </span>
          <i v-if="isFetching" class="el-icon-loading" color="#409EFF"></i>
          <div v-else class="tags_xiaofei">
            <table style="border-collapse: separate; border-spacing: 0px 20px">
              <tr>
                <td class="tag_class">消费能力</td>
                <td>
                  <el-radio-group v-model="clerkVo.bg2" class="tag_list">
                    <el-radio
                      v-for="item in tagsXfNengli"
                      class="tag_item"
                      :label="item.id"
                      style="margin: 0px 0px 0px 0px">
                      {{ item.tag }}
                    </el-radio>
                  </el-radio-group>
                </td>
              </tr>
              <tr v-for="item in tagsXiaoFei">
                <td class="tag_class">{{ item.name }}</td>
                <td>
                  <div class="tag_list">
                    <div v-for="tag in item.tags" class="tag_item">
                      <div class="tag_name">
                        <el-checkbox v-model="tag.checked" @change="handleClickTagItem(tag)">{{ tag.tag }}</el-checkbox>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </el-tab-pane>
        <el-tab-pane :name="cards.tagCustomize">
          <span slot="label">
            <i class="el-icon-s-flag"></i>
            其他标签
          </span>
          <i v-if="isFetching" class="el-icon-loading" color="#409EFF"></i>
          <div v-else class="tags_xiaofei">
            <table style="border-collapse: separate; border-spacing: 0px 20px">
              <tr>
                <td class="tag_class">自建标签</td>
                <td>
                  <div class="tag_list">
                    <div v-for="tag in tagsCustomize" class="tag_item">
                      <div class="tag_name">
                        <el-checkbox v-model="tag.checked">{{ tag.tag }}</el-checkbox>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-divider></el-divider>
    <div class="clerk_tags_footer">
      <div>
        <el-button v-if="isUpdating" type="primary" style="width: 200px" icon="el-icon-loading" disabled>
          {{ EditMode.m == EditMode.AddNewClerk ? '添加顾客' : '修改信息' }}
        </el-button>
        <el-button v-else type="primary" style="width: 200px" @click.stop="handleCommitTag">
          {{ EditMode.m == EditMode.AddNewClerk ? '添加顾客' : '修改信息' }}
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import * as apiSts from '@/api/_com_';
import * as actApi from '@/api/activity';
import * as ctgApi from '@/api/tags_clerk';
import { addClerk2, editClerk } from '@/api/txs';
import TagGategory from '@/utils/enum/tag-gategorys';
import { MessageBox } from 'element-ui';
import { mapGetters } from 'vuex';
import ClerkInfo from './ClerkInfo.vue';

const EditMode = { m: 0, EditTagOnly: 0, AddNewClerk: 1, EditClerk: 2 };

export default {
  name: 'ClerkTags',
  components: { 'clerk-info': ClerkInfo },
  filters: {},
  props: {
    mode /* 是否为全编模式, 0-只修改标签; 1-新增; 2-编辑 */: {
      type: Number,
      required: false,
      default: EditMode.EditTagOnly,
    },
  },
  data() {
    return {
      cards: {
        now: 'tagXingQu',
        baseInfo: 'baseInfo',
        tagXingQu: 'tagXingQu',
        tagXiaoFei: 'tagXiaoFei',
        tagCustomize: 'tagCustomize',
      },
      isFetching: false,
      isUpdating: false,
      EditMode: EditMode,
      tagsXingQu: [],
      tagsXiaoFei: [],
      tagsXfNengli: [], // 消费能力 {tag}
      tagsCustomize: [],
      clerkVo: {}, // 收集标签数据
      clerkTags: {}, // 用于管理 el-rate
      clerkEditVo: {}, // 编辑模式下, 传给基本信息页面的数据
      tagsCodeOnWeb: {
        XinRen: -101, // UI上使用的编码: 信任
        XfNengli: -102, // UI上使用的编码: 消费能力
        XfDengJi: -103, // UI上使用的编码: 消费等级
        NianLing: -104, // UI上使用的编码: 年龄段
      },
    };
  },
  computed: {
    ...mapGetters(['name', 'id', 'deptId', 'openId']),
  },
  created() {
    this.EditMode.m = this.mode;
  },
  mounted() {
    // this.loadAllTagDefinations();
  },
  methods: {
    handleClickCard: async function (tab, event) {
      if (tab.name === this.cards.tagXingQu) {
        return;
      } else if (tab.name === this.cards.tagXiaoFei) {
        return;
      } else if (tab.name === this.cards.tagCustomize) {
        return;
      }
    },
    /**
     * 处理 Rate 组件不能取消第一颗星星的问题
     *
     * @param {string} name 属性名
     * @param {Event} event 发生点击事件的星星标签
     */
    handleChangeTagXingQu: async function (name, event) {
      const target = event.target;
      const preScore = this.clerkTags[name];
      if (preScore === 1 && target.classList && target.classList.contains('el-icon-star-on')) {
        this.clerkVo[name] = 0;
        this.clerkTags[name] = 0;
      } else {
        this.clerkTags[name] = this.clerkVo[name];
      }
    },
    handleClickTagItem: async function (tag) {
      // console.log('handleClickTagItem', tag);
    },
    handleCommitTag: async function () {
      this.collectData();
      if (this.EditMode.m === EditMode.EditTagOnly) {
        await this.goUpdateClerk();
        this.$emit('close', 'close');
      } else {
        const clerkBaseInfo = this.$refs.refClerkInfo.getClerkBaseInfo();
        if (clerkBaseInfo === undefined) {
          return;
        }
        for (const k in clerkBaseInfo) {
          if (clerkBaseInfo.hasOwnProperty(k)) {
            this.clerkVo[k] = clerkBaseInfo[k];
          }
        }
        if (this.EditMode.m === EditMode.AddNewClerk) {
          this.clerkVo.creator = this.name;
          this.clerkVo.checked = 0;
          await this.goCreateClerk();
        } else {
          await this.goUpdateClerk();
        }
        this.$emit('close', 'close');
      }
    },
    resetData() {
      this.tagsXingQu.splice(0, this.tagsXingQu.length);
      this.tagsXiaoFei.splice(0, this.tagsXiaoFei.length);
      this.tagsXfNengli.splice(0, this.tagsXfNengli.length);
      this.tagsCustomize.splice(0, this.tagsCustomize.length);
    },
    collectData() {
      // 消费能力
      this.clerkVo.bg2;
      // 消费意愿: 'xfyy' + TagV1 的 id = TagV2 的 name
      const xfyy = this.tagsXiaoFei.find(x => x.code == TagGategory.TAG_101_200_XF_YI_YUAN.id);
      if (xfyy) {
        const bg3 = xfyy.tags
          .filter(x => x.checked)
          .map(x => x.name.substring('xfyy'.length))
          .join(' ');
        this.clerkVo.bg3 = !bg3 ? null : bg3;
      }
      // 曾经消费: 'cjxf' + TagV1 的 id = TagV2 的 name
      const cjxf = this.tagsXiaoFei.find(x => x.code == TagGategory.TAG_101_200_XF_CENG_JING.id);
      const bg4 = cjxf.tags
        .filter(x => x.checked)
        .map(x => x.name.substring('cjxf'.length))
        .join(' ');
      this.clerkVo.bg4 = !bg4 ? null : bg4;
      // 其他标签: TagV2 新增的
      // 升单品类
      const xqwj = this.tagsXiaoFei.find(x => x.code == TagGategory.TAG_101_200_XU_QIU.id);
      let xqwjTags = undefined;
      if (xqwj) {
        xqwjTags = xqwj.tags.filter(x => x.checked).map(x => x.name);
      }
      // 自建标签
      const customizeTags = this.tagsCustomize.filter(x => x.checked).map(x => x.name);
      const tagsV2 = [];
      if (xqwjTags && xqwjTags.length) {
        tagsV2.push(...xqwjTags);
      }
      if (customizeTags && customizeTags.length) {
        tagsV2.push(...customizeTags);
      }
      this.clerkVo.customizeTags = tagsV2.length === 0 ? null : tagsV2.join(',');
    },
    loadAllTagDefinations: async function () {
      this.tagsXfNengli.push({ id: 0, tag: '超有钱', code: this.tagsCodeOnWeb.XfNengli });
      this.tagsXfNengli.push({ id: 1, tag: '有钱', code: this.tagsCodeOnWeb.XfNengli });
      this.tagsXfNengli.push({ id: 2, tag: '普通', code: this.tagsCodeOnWeb.XfNengli });
      this.tagsXfNengli.push({ id: 3, tag: '没钱', code: this.tagsCodeOnWeb.XfNengli });
      const errAlertMsg = '查询标签失败';
      await actApi
        .getAllBaseTagsNoCount()
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          for (const k in res.data.data.gategoryTags) {
            if (!res.data.data.gategoryTags.hasOwnProperty(k)) {
              continue;
            }
            const v = res.data.data.gategoryTags[k];
            if (!v || !v.length) {
              continue;
            }
            for (const tag of v) {
              tag.checked = undefined;
            }
            const key = Number.parseInt(k);
            switch (key) {
              case TagGategory.TAG_1_100_XING_QU.id:
                this.tagsXingQu.push(...v);
                break;
              case TagGategory.TAG_101_200_XF_NENG_LI.id:
              case TagGategory.TAG_101_200_XF_YI_YUAN.id:
              case TagGategory.TAG_101_200_XF_CENG_JING.id:
              case TagGategory.TAG_101_200_XU_QIU.id:
                this.tagsXiaoFei.push({ code: k, name: res.data.data.gategory[k], tags: v });
                break;
              case TagGategory.TAG_CUSTOMIZE.id:
                this.tagsCustomize.push(...v);
            }
          }
        })
        .catch(err => {
          console.log('loadAllTagDefinations', err);
          MessageBox.alert(errAlertMsg);
        });
    },
    loadTags: async function (clerk) {
      if (this.isFetching) {
        return;
      }
      this.isFetching = true;
      const errAlertMsg = '查询顾客标签失败';
      this.resetData();
      await this.loadAllTagDefinations();
      if (this.EditMode.m === EditMode.AddNewClerk) {
        this.isFetching = false;
        return;
      }
      this.clerkVo = Object.assign({}, clerk);
      await ctgApi
        .get(clerk.id)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
          const ret = res.data.data;
          // console.log(ret);
          for (const k in ret) {
            if (!ret.hasOwnProperty(k)) {
              continue;
            }
            const v = ret[k];
            if (!v || !v.length) {
              continue;
            }
            const key = Number.parseInt(k);
            switch (key) {
              case TagGategory.TAG_1_100_XING_QU.id:
                break; // 兴趣标签, 在入参 clerk  中已包含
              case TagGategory.TAG_101_200_XF_NENG_LI.id:
              case TagGategory.TAG_101_200_XF_YI_YUAN.id:
              case TagGategory.TAG_101_200_XF_CENG_JING.id:
              case TagGategory.TAG_101_200_XU_QIU.id:
                const xft = this.tagsXiaoFei.find(x => x.code === k);
                if (!xft || !xft.tags) {
                  break;
                }
                for (const t of xft.tags) {
                  for (const x of v) {
                    if (x.tagName === t.name) {
                      t.checked = true;
                    }
                  }
                }
                break;
              case TagGategory.TAG_CUSTOMIZE.id:
                for (const t of this.tagsCustomize) {
                  for (const x of v) {
                    if (x.tagName === t.name) {
                      t.checked = true;
                    }
                  }
                }
                break;
            }
          }
        })
        .catch(err => {
          console.log('loadTags', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isFetching = false;
        });
    },
    goCreateClerk: async function () {
      if (this.isUpdating) {
        return;
      }
      this.isUpdating = true;
      const dataInfo = new FormData();
      dataInfo.append('files', null);
      dataInfo.append('clk', JSON.stringify(this.clerkVo));
      const errAlertMsg = '创建顾客失败';
      await addClerk2(dataInfo)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
        })
        .catch(err => {
          console.log('addClerk2', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
    goUpdateClerk: async function () {
      if (this.isUpdating) {
        return;
      }
      this.isUpdating = true;
      const errAlertMsg = this.EditMode.m == EditMode.EditTagOnly ? '更新顾客标签失败' : '更新顾客信息失败';
      await editClerk(this.clerkVo)
        .then(res => {
          if (res.data.status !== apiSts.ResponseOK) {
            if (res.data.message) {
              MessageBox.alert(res.data.message);
            } else {
              MessageBox.alert(errAlertMsg);
            }
            return;
          }
        })
        .catch(err => {
          console.log('editClerk', err);
          MessageBox.alert(errAlertMsg);
        })
        .finally(() => {
          this.isUpdating = false;
        });
    },
    addOrEditClerk: async function (clerk) {
      if (clerk) {
        this.clerkEditVo = Object.assign({}, clerk);
        this.EditMode.m = EditMode.EditClerk;
        await this.$nextTick();
      } else {
        this.EditMode.m = EditMode.AddNewClerk;
      }
      this.cards.now = this.cards.baseInfo;
      this.loadTags(clerk);
    },
    editClerkTags: async function (clerk) {
      this.EditMode.m = EditMode.EditTagOnly;
      this.cards.now = this.cards.tagXingQu;
      this.loadTags(clerk);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/scrollbar.scss';

$font-family: 思源黑体 微软雅黑 Noto Sans SC-Medium;
$title-width: 100px;
$tag-height: 17px;
$tag-line-height: 17px;

.clerk_tags__ {
  width: 100%;
  height: 100vh;
  background-color: beige;
  opacity: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
}

.tags_cards {
  width: 100%;
  height: 85vh;
  padding: 0 10px 0 0;
  display: block;
  overflow-x: hidden;
  overflow-y: hidden;

  .tags_xingqu {
    width: 100%;
    height: 78vh;
    padding: 10px 30px 0 30px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
    gap: 5px;
    overflow-x: hidden;
    overflow-y: scroll;

    .tags_xq_item {
      width: 80%;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      gap: 20px;

      .name {
        color: #333333;
        font-weight: bold;
      }
    }
  }

  .tags_xiaofei {
    display: block;
    text-align: left;
    padding: 10px 30px 0 30px;
    overflow-x: hidden;
    overflow-y: scroll;

    .tag_class {
      width: $title-width;
      font-size: 17px;
      font-weight: 550;
      line-height: 17px;
      letter-spacing: 0px;
      font-variation-settings: 'opsz' auto;
      font-feature-settings: 'kern' on;
      color: #333333;
      letter-spacing: 1px;
      vertical-align: top;
    }

    .tag_list {
      width: 100%;
      height: auto;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: flex-start;
      align-items: center;
      gap: 5px;
    }

    .tag_item {
      margin: 0 0 0 0;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;
      gap: 0px;
    }

    .tag_name {
      width: auto;
      height: $tag-height;
      padding: 0 15px 0 0;
      line-height: $tag-line-height;
      text-align: center;
      font-size: 17px;
      font-weight: normal;
      line-height: 17px;
      letter-spacing: 0px;
      font-variation-settings: 'opsz' auto;
      font-feature-settings: 'kern' on;
      color: #666666;
    }
  }
}

.clerk_tags_footer {
  width: 100%;
  height: 15vh;
  padding: 0 0 5px 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;
}
</style>
